<?php
namespace addons\facrm\controller\facrm\clues;


use addons\facrm\library\BackendApi;
use app\admin\model\AuthGroup;
use app\admin\model\facrm\Fields;

use fast\Tree;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 * 管理线索
 */
class Index extends BackendApi
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'id,name,mobile,telephone';
    protected $childrenAdminIds = [];
    protected $noNeedRight = ['selectpage', 'getImportTpl'];
    protected $addon_config = array();
    protected $modelValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\Clues();
        $this->addon_config = get_addon_config('facrm');
        $this->view->assign("levelList", $this->addon_config['level']);
        $this->view->assign("industryList", $this->addon_config['industry']);
        $this->view->assign("sourceList", $this->addon_config['source']);
        $this->view->assign("record_type_list", $this->addon_config['record_type']);
        $this->request->filter(['strip_tags']);
    }

    /**
     * 线索列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $scene = model('\app\admin\model\facrm\Scene');
        $scene_list = $scene->where('types', 'clues')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->column('id,name');


        $filter_w = $this->getFilterWhere($scene_list);
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            $this->request->request(['custom' => $filter_w]);
            return parent::selectpage();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $total = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'ownerUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
            ])
            ->order($sort, $order)->fetchSql(false)
            ->count();

        $list = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'ownerUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();

        if ($this->addon_config['show_contacts'] != 1) {
            $pattern = '/(\d{3})(\d{4})(\d{4})/i';
            $replacement = '$1****$3';
            //为了安全隐藏手机和电话
            foreach ($list as $row) {
                $row->mobile =$row->mobile?preg_replace ($pattern,$replacement,$row->mobile ):'';
                $row->telephone =$row->telephone?preg_replace ($pattern,$replacement,$row->telephone ):'';
            }
        }


        $result = array("total" => $total, "rows" => $list);
        $this->success('',array( "rows" => $list,'scene'=>$scene_list));

    }

    /**
     * 处理过滤where条件
     * @return array
     */
    private function getFilterWhere($scene_list)
    {

        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        $filter_w['owner_user_id'] = $this->auth->id;
        $filter['scene_id'] = isset($filter['scene_id']) ? $filter['scene_id'] : 10;
        if (isset($filter['scene_id'])) {

            if (!isset($scene_list[$filter['scene_id']])) {
                $this->error(__("您没有权限"));
            }
            switch ($filter['scene_id']) {
              
                case 11:
                    //我的
                    $filter_w['owner_user_id'] = $this->auth->id;
                    break;
                case 12:
                    //下属
                    $this->childrenAdminIds = $this->auth->getChildrenAdminIds(false);
                    if ($this->childrenAdminIds)//修复没有下属的时候获得公共客户
                        $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                    break;
			  case 10:
				//全部
                default:
					$this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
					if ($this->childrenAdminIds)
						$filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
            }
            unset($filter['scene_id']);
            $this->request->get(['filter' => json_encode($filter)]);
        }
        return $filter_w;
    }


    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $params = $this->request->post("row/a");

        
        if ($params) {
			$params = array_merge($params, [
				'create_user_id' => $this->auth->id,
				'owner_user_id' => $this->auth->id,
				'province' => ($this->request->param('province')),
				'city' => ($this->request->param('city')),
				'area' => ($this->request->param('area')),
				'next_time' => strtotime($params['next_time']),
				'follow_time' => time(),
				'collect_time' => time(),
			]);
      

            $result = false;
            Db::startTrans();
            try {
                $params = array_merge($params, [
                    'create_user_id' => $this->auth->id,
                    'owner_user_id' => $this->auth->id
                ]);
                $result = $this->model->add($params);
                Db::commit();
            } catch (ValidateException $e) {

                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {

                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {

                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error($this->model->getError()?__($this->model->getError()):__('添加失败'));
            }
        }
        $this->error(__('参数不能为空', ''));
    }

    /**
     * 修改线索
     * @param null $ids
     */
    public function edit($ids = NULL)
    {
		$ids=$this->request->request('ids','','intval');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkCluesAuth($row, $this->auth)) {
            $this->error(__('您没有权限'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params = array_merge($params, [
                'province' => ($this->request->param('province')),
                'city' => ($this->request->param('city')),
                'area' => ($this->request->param('area')),
            ]);


            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $result =  $row->edit($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($row->getError() ? __($row->getError()) : __('修改失败'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
		$this->success('', $row);
    

    }

    /**
     * 删除
     * @param string $ids
     */
    public function del($ids = "")
    {
		$ids=$this->request->request('ids','','intval');
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $list = $this->model->where($pk, 'in', $ids)->where('owner_user_id', 'in', $this->childrenAdminIds)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 线索池
     */
    public function common()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $filter_w['owner_user_id'] = 0;
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $total = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
            ])
            ->order($sort, $order)->fetchSql(false)
            ->count();
        $list = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        foreach ($list as $row) {
            //公海为了安全隐藏手机和电话
            $row->mobile = "***";
            $row->telephone = "***";
        }

        $result = array("total" => $total, "rows" => $list);
        $this->success('',$result);

    }

    /**
     * 丢弃(放入线索池)
     * @param null $ids
     */
    public function discard($ids = NULL)
    {
		$ids=$this->request->request('ids','','intval');
        $list = $this->model->where('id', 'in', $ids)->select();

        if (!$list) {
            $this->error(__('No Results were found'));
        }
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $success_num = 0;//成功数量
        foreach ($list as $row) {
            if (!in_array($row['owner_user_id'], $this->childrenAdminIds)) {
                $this->error(__("您没有权限ID:{$row->id},成功放入公共{$success_num}条"));
            }
            $row->discard();
            $success_num++;
        }
        $this->success("成功放入公共{$success_num}条");
    }

    /**
     * 领取
     * @param null $ids
     */
    public function receive($ids = NULL)
    {
		$ids=$this->request->request('ids','');
        $success_num = 0;//成功领取的数量
        $error_num = 0;//失败数量
        $error_ids="";//失败的ids
        $msg="";//返回消息

        Db::startTrans();
        try {
            $list = $this->model->where('id', 'in', $ids)->lock(true)->select();
            if (!$list) {
                \exception(__('No Results were found'));
            }
            foreach ($list as $row) {
                if ($row['owner_user_id']) {
                    $error_num++;
                    $error_ids=$error_ids?$error_ids.",".$row->id:$row->id;
                    continue;
                }
                $row->owner_user_id = $this->auth->id;
                $row->collect_time = time();
                $row->save();

                $success_num++;

            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $msg=$msg?$msg:__("成功领取{:success_num}条,失败{:error_num}".($error_num?",失败ids:{:error_ids}":''),
            [
            'success_num'=>$success_num,
            "error_num"=>$error_num,
            'error_ids'=>$error_ids
        ]);
        $this->success($msg);
    }

    /**
     * 转移
     * @param string $ids
     */
    public function divert($ids = NULL)
    {
		$ids=$this->request->request('ids','');
		
        if (!$ids)
            $this->error(__("请选择"));
        $admin_id = $this->request->post("admin_id", '', 'intval');


        if (!$admin_id)
            $this->error(__("未选择员工"));

        $childrenAdminId=$this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $list = $this->model->where('id', 'in', $ids)->where(function ($query) use ($childrenAdminId) {
            $query->where('owner_user_id' , 'in', $this->childrenAdminIds)->whereor('owner_user_id', 0);
        })->fetchSql(false)->select();

        //判断转移的员工是不是下属
        if (!in_array($admin_id, $this->childrenAdminIds)) {
            $this->error(__('只能转移给自己或者下属'));
        }

        if (!$list) {
            $this->error(__('No Results were found'));
        }
        $success_num = 0;//成功数量
        foreach ($list as $row) {

            //转移不限制员工拥有数量。
            $row->owner_user_id = $admin_id;
            $row->save();
            $success_num++;
        }
        $this->success(__("成功转移{$success_num}条"));



    }

    /**
     * 转成客户[get获取|post提交]
     */
    public function transform($ids = NULL){
 
 
		$params = $this->request->post("row/a");
		
		$ids=isset($params['ids'])?$params['ids']:0;
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $row = $this->model->where('id',  $ids)->where(function ($query)  {
            $query->where('owner_user_id' , 'in', $this->childrenAdminIds)->whereor('owner_user_id', 0);
        })->fetchSql(false)->find();

        if (!$row)
            $this->error(__("线索不存在"));
        if ($row->customer_id){
            $this->error(__("该线索已经转成客户"));
        }
        //判断是否有客户限制
        $customerModel = new \app\admin\model\facrm\Customer();

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['owner_user_id']=(isset($params['owner_user_id'])&&$params['owner_user_id'])?$params['owner_user_id']:$this->auth->id;
            //判断转移的员工是不是下属
            if (!in_array($params['owner_user_id'], $this->childrenAdminIds)) {
                $this->error(__('只能归属给自己或者下属'));
            }

            if ($this->addon_config['possess_num'] > 0 &&
                $this->addon_config['possess_num'] <= $customerModel->where('deal_status', 0)->where('owner_user_id', $params['owner_user_id'])->count()) {
                $this->error(__("已经超过限制拥有客户数量,限制") . $this->addon_config['possess_num']);
            }


            $params = array_merge($params, [
                'create_user_id' => $this->auth->id,
                'province' => intval($this->request->param('province')),
                'city' => intval($this->request->param('city')),
                'area' => intval($this->request->param('area')),
                'next_time' => strtotime($params['next_time']),
                'follow_time' => time(),
                'collect_time' => time(),
            ]);
            if ($params) {
   
                $result = false;
                Db::startTrans();
                try {
                    $result = $customerModel->add($params);
                    if ($result){
                        $row->customer_id=$result;
                        $row->status=1;
                        $row->save();
                        $recordModel = model('\app\admin\model\facrm\Record');
                        $recordModel->where('types','clues')->where('types_id',$row->id)->update([
                            'types'  => 'customer',
                            'types_id' =>$result,
                        ]);
                        $recordFiles = model('\app\admin\model\facrm\record\Files');
                        $recordFiles->where('types','clues')->where('types_id',$row->id)->update([
                            'types'  => 'customer',
                            'types_id' =>$result,
                        ]);
                    }
                    Db::commit();
                } catch (ValidateException $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($customerModel->getError()?__($customerModel->getError()):__('添加失败'));
                }
            }
            $this->error(__('参数不能为空', ''));
        }

        $this->success('',$row);
    }


    /**
     * selectpage
     * @Internal
     * @return \think\response\Json
     */
    public function selectpage()
    {
        $type = $this->request->param('type');
        if ($type == "all") {
            return parent::selectpage(); // TODO: Change the autogenerated stub
        } else {
            return $this->index();
        }
    }





    /**
     *批量导入
     */
    public function import()
    {
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $this->groupList = $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');

            if (!$params['file']) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . DS . 'public' . DS . $params['file'];

            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            $owner_user_ids = [];
            //如果选择了组、没有选择成员 自动分配客户
            if (!$params['owner_user_id'] && $params['group_id']) {
                $childrenGroupIds = $this->auth->getChildrenGroupIds(true);
                Tree::instance()->init($this->groupList);
                $groupIds = Tree::instance()->getChildrenIds($params['group_id'], true);

                $authGroupList = \app\admin\model\AuthGroupAccess::
                field('uid,group_id')
                    ->where('group_id', 'in', $groupIds)
                    ->select();
                foreach ($authGroupList as $k => $v) {
                    if (in_array($v['uid'], $owner_user_ids)) continue;
                    $owner_user_ids[] = $v['uid'];
                }
                if (!$owner_user_ids) {
                    $this->error("没有数据");
                }
            } else {
                $owner_user_ids = explode(',', $params['owner_user_id']);
            }


            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
            } elseif ($ext === 'xls') {
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
            } else {
                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");

            }

            $table = $this->model->getQuery()->getTable();
            $database = \think\Config::get('database.database');
            $fieldArr = [];
            $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
            foreach ($list as $k => $v) {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            }


            //加载文件
            $insert = 0;
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields = [];
                for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $fields[] = $val;
                    }
                }

                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = [];
                    $temp = array_combine($fields, $values);
                    foreach ($temp as $k => $v) {
                        if (isset($fieldArr[$k]) && $k !== '') {
                            if (in_array($fieldArr[$k], $this->filter_column)) continue;
                            $row[$fieldArr[$k]] = $v;
                            //随机分配客户
                            if ($fieldArr[$k] == 'owner_user_id' && !$v && $owner_user_ids) {
                                $row[$fieldArr[$k]] = $owner_user_ids[mt_rand(0, count($owner_user_ids) - 1)];
                            }
                            if ($fieldArr[$k] == 'create_user_id' && !$v) {
                                $row[$fieldArr[$k]] = $this->auth->id;
                            }
                            //创建
                        }
                    }
                    if ($row) {
                        $result=$this->model->add($row);
                        if ($result){
                            $insert++;
                        }else if (!$result&&$params['skip']!=1){
                            \exception($this->model->getError()?__($this->model->getError()):__('添加失败'));
                        }
                    }
                }
            } catch (\Exception $exception) {
                $this->error($exception->getMessage() . "行数：" . $currentRow);
            } catch (ValidateException $e) {
                $this->error($e->getMessage() . "行数：" . $currentRow);
            }
            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            $this->success(__("成功导入{:insert}条",['insert'=>$insert]));
        }


        Tree::instance()->init($groupList);
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        $groupdata[0] = '选择归属组';
        $this->view->assign('groupdata', $groupdata);
        return $this->view->fetch();
    }

    /**
     * 需要过滤导入的字段
     * @var string[]
     */
    protected $filter_column = ['id', 'status', 'customer_id', 'delete_time', 'create_time', 'update_time', 'delete_time', 'collect_time'];

    /**
     * 获取导入模板
     * @throws PDOException
     * @throws \think\db\exception\BindParamException
     */
    public function getImportTpl()
    {

        $table = $this->model->getQuery()->getTable();

        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $i = 0;
        foreach ($list as $k => $v) {
            if (in_array($v['COLUMN_NAME'], $this->filter_column)) continue;
            if ($i >= 26) {
                $cell = chr(65 + $i / 26 - 1) . chr(65 + $i % 26);
            } else {
                $cell = chr(65 + $i);
            }
            $sheet->setCellValue($cell . '1', $v['COLUMN_COMMENT']);
            $i++;
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        //header('Content-Type:application/vnd.ms-excel');//输出03版本
        header("Content-Disposition: attachment;filename=customertpl" . date('Ymd') . '.xlsx');
        header('Cache-Control: max-age=0');
        header('Cache-Control: cache, must-revalidate');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        try {
            $writer->save('php://output');
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }

        exit();

    }

    /**
     * 下一条
     */
    public function next($type='owner'){
        $cachename=$this->auth->id.'cluescachenextid';
        $prev_id=intval(cache($cachename));
        //自动获取我待跟进的客户
        if ($prev_id){
            $this->model->where('id','>',$prev_id);
        }
        switch ($type){
            case 'all':
                $childrenAdminIds =$this->auth->getChildrenAdminIds(true);
                $this->model->where('owner_user_id','in',$childrenAdminIds);
                break;
            case 'owner';
            default:
                $this->model->where('owner_user_id',$this->auth->id);
        }


        $row= $this->model->where([function ($q){
            return $q->where('next_time','<>','')->where('next_time','<',time())->whereOr('follow_time','');
        }])->fetchSql(false)->order('id asc')->field('id,name')->find();

        if (!$row){
            cache($cachename,null);
            $this->error(__("没有下一条了"));
        }
        cache($cachename,$row->id);
        $this->success("",$row);
    }
}
